<template>
  <div class="search-suggestion">
      <van-cell
      icon="search"
      v-for="(item,index) in suggestions"
      :key="index"
      @click="$emit('search',item)"
      >
      <div slot="title" v-html="highlight(item)"></div>
      </van-cell>
  </div>
</template>
<script>
import { getSearchSuggestions } from "@/api/search"
import { debounce } from "lodash"
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data: () => ({
    suggestions: []
  }),
  watch: {
    searchText: {
      handler: debounce(async function () {
        const res = await getSearchSuggestions(this.searchText)
        this.suggestions = res.data.data.options
      }, 200),
      immediate: true
    }
  },
  component: {
    getSearchSuggestions
  },
  methods: {
    highlight (item) {
      return item.replace(new RegExp(this.searchText, 'gi'), `<span style='color: red'>${this.searchText}</span>`)
    }
  }
}
</script>
<style lang="less" scoped>
</style>